package com.wondertek.poms.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
@Component
public class HttpUtils {
    public static boolean doPost(String url, Object returnVo, String successValue, String successAttr) {
        String json = JSON.toJSONString(returnVo);
        boolean flag = false;
        for (int i = 0; i < 3; i++) {
            String result = httpPost(url, json);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jo = JSONObject.parseObject(result);
                log.info("发布推送能力平台接口的URL===入参为:" + json + "第  " + i + "  次http请求==返回值：" + jo.getString(successValue));
                if (successAttr.equals(jo.getString(successValue))) {
                    flag=true;
                    break;
                }
            }
        }
        return flag;
    }

    public static String httpPost(String url, String json) {
        PostMethod method = new PostMethod(url);
        HttpClient httpClient = new HttpClient();
        try {
            HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
            managerParams.setConnectionTimeout(10000);
            managerParams.setSoTimeout(10000);
            RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
            method.setRequestEntity(entity);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                log.error("HttpClient Error==[入参:" + json + "[statusCode = " + statusCode + "");
                return "";
            }
            InputStream in = method.getResponseBodyAsStream();
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for (int n; (n = isr.read(b)) != -1;) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return returnStr;
        } catch (Exception e) {
            log.error("====发布推送能力平台接口的URL失败======" + json);
            e.getStackTrace();
        } finally {
            method.releaseConnection();
        }

        return "";
    }
}
